﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading;
using System.Threading.Tasks;
using TradingServer.Core.Entities;

namespace Sample
{
	public class Scalper
	{
		public Scalper(Security security, decimal startPrice, bool isBull, int seed)
		{
			_security = security;
			_startPrice = startPrice;
			_isBull = isBull;
			_seed = seed;
			Low = _startPrice - _startPrice / 2;
			High = _startPrice + _startPrice / 2;
		}

		public void Start()
		{
			_active = true;
		}

		public void Stop()
		{
			_active = false;
		}

		public decimal StartPrice
		{
			get { lock (_locker) return _startPrice; }
			set { lock (_locker) _startPrice = value; }
		}

		public decimal Low { get; set; }
		public decimal High { get; set; }

		public void Run()
		{
			OrderGlass glass = OrderGlassFactory.Get(_security);
			glass.TradeCreated += OnTradeCreated;
			Random rnd = new Random(_seed);
			while (_active)
			{
				decimal low = _startPrice <= Low ? 0 : (_startPrice - Low) / 10;
				decimal high = _startPrice >= High ? 0 : (High - _startPrice) / 10;
				int price = rnd.Next((int)(_startPrice - low) * 100, (int)(_startPrice + high) * 100);
				int volume = rnd.Next(100, 2000);
				OrderType type = _isBull ? OrderType.Buy : OrderType.Sell;
				Order order = new Order(type, _security, volume, (decimal) price / 100M);
				order.Put(TimeSpan.FromSeconds(10));

				int delay = rnd.Next(1500, 3000);
				Thread.Sleep(delay);
			}
			glass.TradeCreated -= OnTradeCreated;
		}

		#region Private members

		private readonly Security _security;
		private decimal _startPrice;
		private volatile bool _active = false;
		private bool _isBull;
		private object _locker = new object();
		private int _seed;

		void OnTradeCreated(Trade trade, EventArgs args)
		{
			lock (_locker) _startPrice = trade.Price;
		}

		#endregion
	}
}
